import React from "react";
import "./FilterBar.css";

export type FilterOption = {
  label: string;
  value: string;
};

export type FilterGroup = {
  key: string;
  label: string;
  type?: "single" | "multi";
  options: FilterOption[];
};

interface FilterBarProps {
  groups: FilterGroup[];
  value: Record<string, string | string[]>;
  onChange: (val: Record<string, string | string[]>) => void;
}

const FilterBar: React.FC<FilterBarProps> = ({ groups, value, onChange }) => {
  const handleSelect = (groupKey: string, optionValue: string, type: "single" | "multi" = "single") => {
    let newValue = { ...value };
    if (type === "single") {
      newValue[groupKey] = optionValue;
    } else {
      const arr = Array.isArray(newValue[groupKey]) ? [...(newValue[groupKey] as string[])] : [];
      if (arr.includes(optionValue)) {
        newValue[groupKey] = arr.filter(v => v !== optionValue);
      } else {
        arr.push(optionValue);
        newValue[groupKey] = arr;
      }
    }
    onChange(newValue);
  };

  return (
    <div className="filter-bar">
      {groups.map(group => (
        <div className="filter-group" key={group.key}>
          <span className="filter-group-label">{group.label}：</span>
          <div className="filter-options">
            {group.options.map(opt => {
              const selected =
                group.type === "multi"
                  ? Array.isArray(value[group.key]) && (value[group.key] as string[]).includes(opt.value)
                  : value[group.key] === opt.value;
              // 格式多选用checkbox风格
              const isCheckbox = group.type === "multi";
              return (
                <span
                  key={opt.value}
                  className={`filter-option${selected ? " selected" : ""}${isCheckbox ? " checkbox" : ""}`}
                  onClick={() => handleSelect(group.key, opt.value, group.type)}
                >
                  {isCheckbox && (
                    <input
                      type="checkbox"
                      checked={selected}
                      readOnly
                      style={{ marginRight: 4 }}
                    />
                  )}
                  {opt.label}
                </span>
              );
            })}
            {/* 颜色筛选特殊处理 */}
            {group.key === "color" && (
              <span className="filter-color">
                <span className="filter-color-circle"></span>
                <span className="filter-color-text">点击左侧，选取不同颜色~</span>
              </span>
            )}
          </div>
        </div>
      ))}
    </div>
  );
};

export default FilterBar;